import tkinter as tk
from tkinter import *
from tools import *
import math
from datetime import datetime

class TabFunc():
    #初始化
    def __init__(self):
        self.tools   = Tools()

    def gen_sql(self, sql, where_exp = '', order_exp = ''):
        """生成SQL
        """
        if sql == '': return ''

        if len(where_exp) == 0:
            sql = sql.replace('<WHERE>', '')
            sql = sql.replace('<where>', '')
        else:
            sql = sql.replace('<WHERE>', 'WHERE ' + where_exp)
            sql = sql.replace('<where>', where_exp)

        if len(order_exp) == 0:    
            sql = sql.replace('<order>', '')
        else:
            sql = sql.replace('<order>', 'ORDER BY ' + order_exp)

        return sql
    
    def check_query(self, query_config):
        """检查查询配置，并添加未配置的项目
        """
        must_have   = 'title'.split(',')
        all_keys    = 'title,where,header,id_field,sql,data,stat_row,print_grf'.split(',')
        true_keys   = 'show_adv_option'.split(',') # 默认为 ture 的项
        false_keys  = 'show_col_check,multiselect'.split(',') #默认为 false 的项

        _keys = query_config.keys()
        # 必填的项
        _err = []
        for item in must_have:
            if self.tools.in_list(_keys, item) == False: _err.append(item)

        if len(_err) > 0:
            s = ','.join(_err)
            self.tools.msg(f"缺少查询配置项:{s}", 'warning')
            return False
        
        # 补上缺少的项
        for item in all_keys:
            if self.tools.in_list(_keys, item) == False: query_config[item] = ''
        for item in true_keys:
            if self.tools.in_list(_keys, item) == False: query_config[item] = True
        for item in false_keys:
            if self.tools.in_list(_keys, item) == False: query_config[item] = False
        # 其他值处理:row_height,query_caption,stat_row_caption,
        if self.tools.in_list(_keys, 'row_height') == False: query_config['row_height'] = 20   # 行高
        s = query_config.get('query_caption', '')
        if len(s) == 0: s = query_config['query_caption'] = '查询'
        s = query_config.get('stat_row_caption', '')
        if len(s) == 0: s = query_config['stat_row_caption'] = '<合计>'

        # 表头
        if len(query_config['header']) > 0:
            all_keys    = 'align,format,order,trans'.split(',')
            # 检查必填项:field
            h_index = 1
            for h in query_config['header']:
                field = h.get('field', '')
                if len(field) == 0:
                    self.tools.msg(f"表头定义[header]中的第{h_index}项[field]为空！", 'warning')
                    return False
                h_index += 1

                _keys = h.keys()
                # 补上缺少的项
                for item in all_keys:
                    if self.tools.in_list(_keys, item) == False: h[item] = ''
                # 其他值处理:caption,width
                caption = h.get('caption', '')
                if len(caption) == 0: h['caption'] = h['field']
                width = h.get('width', 0)
                if int(width) <= 0: h['width'] = 10
        # 统计行
        if len(query_config['stat_row']) > 0:
            pass
        # sql,data 至少有一项
        if len(query_config['sql']) == 0 and len(query_config['data']) == 0:
            self.tools.msg("查询配置项错误:sql,data不能同时为空！", 'warning')
            return False

        return query_config
    
    def check_edit(self, edit_config):
        """检查编辑配置，并添加未配置的项目
        """
        pass

    def format_value(self, value, format):
        """格式化内容
        """
        value = str(value)
        if len(value) == 0 or len(format) == 0: return ''

        str_left = format[0 : 1]
        if str_left == '%': # 日期时间："%Y-%m-%d %H:%M:%S",%开始
            _v = datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
            return _v.strftime(format)
        
        if str_left == ':': # 金额、数字,如“:,.2”
            return ("{" + format + "f}").format(float(value))
        
        if format[0 : 11] == 'sec_to_time': # 秒数转换为时间
            arr = format.split('/')
            if len(arr) == 1:
                return self.sec_to_time(value)
            else:
                return self.sec_to_time(value, arr[1])
            
        if format[0 : 9] == 'file_size': # 友好的文件大小
            arr = format.split('/')
            if len(arr) == 1:
                return self.get_size_desc(value)
            else:
                return self.get_size_desc(value, int(arr[1]))
        # 字典类型 ?
        dic = self.str_to_dict(format)
        if dic:
            return dic.get(str(value), '')

    def get_size_desc(self, size, header = '', decimals = 1):
        """根据文件大小，返回使用不同单位的描述，如：字节、K、M、G
            size     int     字节 
            header   string  前缀
            decimals int     小数柆 
        """
        size = int(size)
        if(size < 1024): return header + str(size) + '字节'
        if(size < 1024*1024): return header + str(round(size/1024, decimals)) + 'K'
        if(size < 1024*1024*1024): return header + str(round(size/1024/1024, decimals)) + 'M'
        return header + str(round(size/1024/1024/1024, decimals)) + 'G'

    def sec_to_time(self, sec, format = ''):
        """生成秒数的描述字符串，如：1时2分3秒
            * sec      int     秒
            * format   string  格式,如：h:m:s、h时m分s秒
        """
        if(len(str(sec)) == 0): return '0'
        if(len(format) == 0): format = 'h:m:s'
        
        sec = int(sec)
        dir = ''
        if(sec < 0):
            dir = '-1'
            sec = 0 - sec

        h = 0
        m = 0
        if(sec >= 3600):	#大于1小时
            h      = math.floor(sec/3600)
            sec    = sec % 3600
            m      = math.floor(sec/60)
            sec  = sec % 60
        else:
            if(sec >= 60):  #大于1分钟
                m   = math.floor(sec/60)
                sec = sec % 60
        
        format = format.replace('h', str(h))
        format = format.replace('m', str(m))
        return dir + format.replace('s', str(sec))
    
    def str_to_dict(self, s):
        """字典类型字符串转字典:1=星期一&2=星期二&3=星期三&4=星期四&5=星期五&6=星期六&7=星期日
        """
        if len(s) == 0: return False

        ret = {}
        lst = s.split('&')
        for item in lst:
            arr = item.split('=')
            if len(arr) == 0:
                ret[arr[0]] = ''
            else:
                ret[arr[0]] = arr[1]

        return ret